package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析映射配置文件类
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml配置文件
     * @param resourceAsStream  mapper.xml配置文件的字节输入流
     */
    public void parse(InputStream resourceAsStream) throws DocumentException {
        // 使用Dom4j解析器解析
        SAXReader reader = new SAXReader();
        Document document = reader.read(resourceAsStream);
        Element rootElement = document.getRootElement();

        // namespace
        String namespace = rootElement.attributeValue("namespace");

        List<Element> elementList = rootElement.selectNodes("//select|//update|//insert|//delete");
        for (Element element : elementList) {
            // 节点名称，即SQL类型
            String name = ((Node) element).getName();

            // ID
            String id = element.attributeValue("id");
            // 参数值类型
            String parameterType = element.attributeValue("parameterType");
            // 返回值类型
            String resultType = element.attributeValue("resultType");
            // SQL语句
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlType(name);

            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
